package com.authine.cloudpivot.app.openapi.gateway;

import cn.hutool.json.JSONUtil;
import com.authine.cloudpivot.app.openapi.config.LocalDebugAppRouteBean;
import com.authine.cloudpivot.app.openapi.config.LocalDebugHeaderParam;
import com.authine.cloudpivot.app.openapi.domain.openapi.UserInfoValue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * @author lifuchun
 */
@Component
@Slf4j
public class RpcManager {


    private final LocalDebugAppRouteBean localDebugAppRouteBean;


    private final RestTemplate restTemplate;

    public RpcManager(LocalDebugAppRouteBean localDebugAppRouteBean, RestTemplate restTemplate) {
        this.localDebugAppRouteBean = localDebugAppRouteBean;
        this.restTemplate = restTemplate;
    }

    public UserInfoValue getUserInfoValue(String userId, String corpId) {


        String baseUrl = localDebugAppRouteBean.getBaseUrl("app-org", LocalDebugHeaderParam.builder()
                .loginId(userId)
                .build());


        Map<String, String> params = new HashMap<>(2);
        params.put("sourceId", userId);
        params.put("corpId", corpId);

        try {

            Map<String, Object> resMap;

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(null, headers);
            String url = baseUrl + "/user/get/sourceid/corpid?sourceId={sourceId}&corpId={corpId}";
            log.info("获取用户信息的url:{}",url);
            ResponseEntity<Map> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Map.class, params);
            resMap = responseEntity.getBody();

            log.info("查询用户信息返回结果:{}，Url:{}", JSONUtil.toJsonPrettyStr(resMap), url);
            return Optional.ofNullable(resMap).filter(item -> Objects.equals(true, item.get("success"))).map(item -> (Map<String, Object>) item.get("data"))
                    .map(item -> {
                        UserInfoValue userInfoValue = UserInfoValue.builder().build();

                        Optional.ofNullable(item.get("userBaseId")).map(String::valueOf).ifPresent(userInfoValue::setBaseUserId);
                        Optional.ofNullable(item.get("corpId")).map(String::valueOf).ifPresent(userInfoValue::setCorpId);
                        Optional.ofNullable(item.get("sourceId")).map(String::valueOf).ifPresent(userInfoValue::setOrgUserId);
                        Optional.ofNullable(item.get("pinYin")).map(String::valueOf).ifPresent(userInfoValue::setRealName);
//                        Optional.ofNullable(item.get("username")).map(String::valueOf).ifPresent(userInfoValue::setUsername);
//                        Optional.ofNullable(item.get("mobile")).map(String::valueOf).ifPresent(userInfoValue::setMobile);
//                        Optional.ofNullable(item.get("mainDepartment")).map(String::valueOf).ifPresent(userInfoValue::setDepartmentName);
//                        Optional.ofNullable(item.get("position")).map(String::valueOf).ifPresent(userInfoValue::setPosition);

                        return userInfoValue;

                    }).orElseThrow(() -> new IllegalArgumentException("解析查询用户信息接口返回值失败"));


        } catch (Exception ex) {
            log.error("获取用户信息接口通信失败,参数：sourceId:{},corpId:{} ", userId, corpId, ex);
            throw new IllegalArgumentException(String.format("获取用户信息失败：参数：sourceId:%s,corpId:%s", userId, corpId));
        }

    }

}
